<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="职位名称" prop="jobName">
        <el-input v-model="formData.jobName" placeholder="请输入职位名称" />
      </el-form-item>
      <el-form-item label="公司名称" prop="companyId">
        <el-select v-model="formData.companyId" placeholder="请选择">
          <el-option
            v-for="item in companyList"
            :key="item.id"
            :label="item.companyName"
            :value="item.id!"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专业" prop="majorId">
        <el-tree
          v-model="formData.majorId"
          :data="deptTree"
          ref="treeRef"
          check-strictly
          default-expand-all
          :props="defaultProps"
          show-checkbox
          placeholder="请选择专业"
          value-key="id"
          node-key="id"
          text-key="name"
        />
      </el-form-item>

      <el-form-item label="届别要求" prop="classRequirements">
        <el-input v-model="formData.classRequirements" placeholder="请输入届别要求" />
      </el-form-item>
      <el-form-item label="最低学历" prop="minEducation">
        <el-input v-model="formData.minEducation" placeholder="请输入最低学历" />
      </el-form-item>
      <el-form-item label="复制链接" prop="address">
        <el-input v-model="formData.url" placeholder="请输入复制链接" />
      </el-form-item>
      <el-form-item label="岗位类型" prop="address">
        <el-input v-model="formData.jobType" placeholder="请输入岗位类型" />
      </el-form-item>
      <el-form-item label="省市区">
        <el-cascader
          v-model="selectedOptions"
          :options="regionData"
          @change="handleChange"
          placeholder="请选择省市区"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="职位描述" prop="jobDetail">
        <Editor v-model="formData.jobDetail" height="150px" />
      </el-form-item>
      <el-form-item label="上架" prop="isShelved">
        <el-radio-group v-model="formData.isShelved">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上架时间" prop="shelvedTime">
        <el-date-picker
          v-model="formData.shelvedTime"
          type="date"
          value-format="x"
          placeholder="选择上架时间"
        />
      </el-form-item>
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-radio-group v-model="formData.isRecommend">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="推荐时间" prop="recommendTime">
        <el-date-picker
          v-model="formData.recommendTime"
          type="date"
          value-format="x"
          placeholder="选择推荐时间"
        />
      </el-form-item>
      <el-form-item label="招聘开始时间" prop="hireBeginTime">
        <el-date-picker
          v-model="formData.hireBeginTime"
          type="date"
          value-format="x"
          placeholder="选择招聘开始时间"
        />
      </el-form-item>
      <el-form-item label="招聘结束时间" prop="hireEndTime">
        <el-date-picker
          v-model="formData.hireEndTime"
          type="date"
          value-format="x"
          placeholder="选择招聘结束时间"
        />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { JobApi, JobVO } from '@/api/member/job'
import { CompanyApi, CompanyVO } from '@/api/member/company'
import {
  regionData, codeToText
} from 'element-china-area-data'
import * as PostApi from "@/api/system/post";
import {MajorApi} from "@/api/member/major";
import {handleTree, defaultProps} from "@/utils/tree";
/** 职位 表单 */
defineOptions({ name: 'JobForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
let selectedOptions = ref([])
const selectedAddress = ref('')
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const companyList = ref([] as CompanyApi.CompanyVO[]) // 岗位列表
const deptTree = ref() // 树形结构
const treeRef = ref() // 菜单树组件 Ref
const formData = ref({
  id: undefined,
  jobName: undefined,
  companyId: undefined,
  classRequirements: undefined,
  minEducation: undefined,
  provinceId: undefined,
  provinceName: undefined,
  cityId: undefined,
  cityName: undefined,
  districtId: undefined,
  districtName: undefined,
  address: undefined,
  jobDetail: undefined,
  majorId: [],
  isShelved: undefined,
  shelvedTime: undefined,
  isRecommend: undefined,
  recommendTime: undefined,
  visitNum: undefined,
  sendNum: undefined,
  hireBeginTime: undefined,
  hireEndTime: undefined
})
const formRules = reactive({
  jobName: [{ required: true, message: '职位名称不能为空', trigger: 'blur' }],
  companyId: [{ required: true, message: '公司ID不能为空', trigger: 'change' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  isShelved: [{ required: true, message: '是否上架不能为空', trigger: 'blur' }],
  isRecommend: [{ required: true, message: '是否推荐不能为空', trigger: 'blur' }],
  hireBeginTime: [{ required: true, message: '招聘开始时间不能为空', trigger: 'blur' }],
  hireEndTime: [{ required: true, message: '招聘结束时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await getTree()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await JobApi.getJob(id)
      // 设置选中
      console.log('11111', formData.value.majorId)
      formData.value.majorId.forEach((majorId: number) => {
        treeRef.value.setChecked(majorId, true, false)
      })
    } finally {
      formLoading.value = false
    }
  }
  // 加载岗位列表
  companyList.value = await CompanyApi.getCompanyList()

}
/** 获得部门树 */
const getTree = async () => {
  deptTree.value = []
  const data = await MajorApi.getSimpleList()
  let dept: Tree = { id: 0, name: '顶级专业', children: [] }
  dept.children = handleTree(data)
  deptTree.value.push(dept)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const handleChange = (value) => {
  formData.value.provinceId = value[0]
  formData.value.cityId = value[1]
  formData.value.districtId = value[2]
  const [province, city, district] = value.map(code => codeToText[code])
  formData.value.provinceName = province
  formData.value.cityName = city
  formData.value.districtName = district
  formData.value.address = `${province} ${city} ${district}`
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as JobVO
    data.majorId = [
      ...(treeRef.value.getCheckedKeys(false) as unknown as Array<number>), // 获得当前选中节点
      ...(treeRef.value.getHalfCheckedKeys() as unknown as Array<number>) // 获得半选中的父节点
    ]
    if (formType.value === 'create') {
      await JobApi.createJob(data)
      message.success(t('common.createSuccess'))
    } else {
      await JobApi.updateJob(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    jobName: undefined,
    companyId: undefined,
    classRequirements: undefined,
    minEducation: undefined,
    provinceId: undefined,
    provinceName: undefined,
    cityId: undefined,
    cityName: undefined,
    districtId: undefined,
    districtName: undefined,
    address: undefined,
    jobDetail: undefined,
    isShelved: undefined,
    shelvedTime: undefined,
    isRecommend: undefined,
    recommendTime: undefined,
    visitNum: undefined,
    sendNum: undefined,
    hireBeginTime: undefined,
    hireEndTime: undefined
  }
  formRef.value?.resetFields()
}
</script>
